package md.frolov.bible.views;

import md.frolov.bible.Constants;
import md.frolov.bible.commands.OpenEditorCommand;
import md.frolov.bible.model.Archive;
import md.frolov.bible.model.IStructure;
import md.frolov.bible.model.IURLProvider;
import md.frolov.bible.model.Module;
import md.frolov.bible.providers.ViewContentProvider;
import md.frolov.bible.providers.ViewLabelProvider;
import md.frolov.bible.sorters.BookSorter;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class BooksView extends ViewPart {
	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action action1;
	private Action action2;
	public static final String PLUGIN_ID = "md.frolov.bible.views.BooksView";

	/**
	 * The constructor.
	 */
	public BooksView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		viewer.setSorter(new BookSorter());
		viewer.setContentProvider(new ViewContentProvider(Module.class,Object.class));
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(Archive.getInstance());
		getSite().setSelectionProvider(viewer);
		makeActions();
		hookContextMenu();
		hookOpenAction();
		hookModulesSelectionChanged();
		contributeToActionBars();
	}
	
	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				BooksView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		action2 = new Action() {
			public void run() {
				showMessage("Action 2 executed");
			}
			
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
	}

	private void hookOpenAction() {
		viewer.addOpenListener(new IOpenListener(){
			@Override
			public void open(OpenEvent event) {
				System.out.println();
				System.out.println("open");
				IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
				if(selection.getFirstElement() instanceof IURLProvider){
					String url = ((IURLProvider)selection.getFirstElement()).getUrl();
					viewer.setData("noPostSelection", "true");
//					return;
					OpenEditorCommand.executeStatic(url);
				}
			}
		});
	}
	
	private void hookModulesSelectionChanged(){
		//we need selectionChangedListenere and postSelectionChangedListener to identify which event was called
		//if there's simple selection, events are called this way:
		//selectionChanged
		//postselection changed
		//if there's open event
		getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(ModulesView.PLUGIN_ID, new ISelectionListener(){
			@Override
			public void selectionChanged(IWorkbenchPart part,ISelection selection) {
				((ModulesView)getSite().getWorkbenchWindow().getActivePage().findView(ModulesView.PLUGIN_ID)).getViewer().setData(Constants.NO_OPEN_EVENT_TRIGGER, "yes");
			}
		});
		
		getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(ModulesView.PLUGIN_ID, new ISelectionListener(){
			@Override
			public void selectionChanged(IWorkbenchPart part, ISelection selection) {
				if(!(part instanceof ModulesView)) return;
				if(selection == null) return;
				if(((ModulesView)getSite().getWorkbenchWindow().getActivePage().findView(ModulesView.PLUGIN_ID)).getViewer().getData(Constants.NO_OPEN_EVENT_TRIGGER)==null) return;
				if(!(selection instanceof IStructuredSelection)) return;
				Object select = ((IStructuredSelection)selection).getFirstElement();
				if(!(select instanceof Module)) return;
				
				IStructuredSelection bookSel = (IStructuredSelection) viewer.getSelection();
				IStructure bookSelection = null;
				if(bookSel != null)
					bookSelection = (IStructure) bookSel.getFirstElement();
				viewer.setInput(select);
				if(bookSelection!=null){
					String id = bookSelection.getId();
					IStructure newSelection = ((Module) select).getById(id);
					if(newSelection == null) newSelection = ((Module) select).getFirstBook().getFirstChapter();
					viewer.setSelection(new StructuredSelection(newSelection),true);
				}
			}
			
		});
	}
	
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Books",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
	
	public TreeViewer getViewer() {
		return viewer;
	}
}